package com.zh.rent.util;

import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.IMAPStore;
import com.sun.mail.imap.protocol.IMAPProtocol;
import org.apache.commons.mail.SimpleEmail;

import javax.mail.*;
import javax.mail.internet.MimeMessage;
import javax.mail.search.FlagTerm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.ProtocolException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class EmailUtil {
    // 随机验证码
    public String achieveCode() {  //由于数字1 和0 和字母 O,l 有时分不清，所有，没有字母1 、0
        String[] beforeShuffle = new String[]{"2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F",
                "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a",
                "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
                "w", "x", "y", "z"};
        List list = Arrays.asList(beforeShuffle);//将数组转换为集合
        Collections.shuffle(list);  //打乱集合顺序
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            sb.append(list.get(i)); //将集合转化为字符串
        }
        return sb.toString().substring(3, 8);  //截取字符串第4到8
    }

    public void sendAuthCodeEmail(String email, String authCode) {
        SimpleEmail simpleEmail = new SimpleEmail();
        //开启SSL加密
        simpleEmail.setSSLOnConnect(true);
        //SMTP服务器的端口
        simpleEmail.setSslSmtpPort("465");
        //SMTP服务器的名字
        simpleEmail.setHostName("smtp.qq.com");
        //发件人邮箱以及授权码
        simpleEmail.setAuthentication("1531744858@qq.com", "fsofqjrabunzgebh");
        //编码集
        simpleEmail.setCharset("UTF-8");

        try {
            //收件人邮箱
            simpleEmail.addTo(email);
            //发件人邮箱以及发件人名称
            simpleEmail.setFrom("1531744858@qq.com", "租号平台:");
            //邮件主题
            simpleEmail.setSubject("租号平台验证码");
            //邮件内容
            simpleEmail.setMsg("尊敬的用户:你好! 租号平台验证码为:" + authCode + "\n" +"     (有效期为一分钟)");
            simpleEmail.send();
        } catch (Exception e) {
           // log.error("发送邮件失败", e);
           // throw new Exception("发送邮件失败");
        }
    }

    //发送验证码，并使用session存储设置值
    public boolean vcode(HttpServletRequest request,String email) {
       // String email = request.getParameter("email");
        String code = new EmailUtil().achieveCode();  //生成随机密码
        try {
            new EmailUtil().sendAuthCodeEmail(email, code);
            HttpSession session = request.getSession();
            session.setAttribute("Vcode", code);
            session.setMaxInactiveInterval(300); //设置session有效期 60秒
            System.out.println("session0000:"+session.getId());
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static List<Map<String,Object>>  Emali (String MailboxName,String Authorization,String Host) throws Exception {
           //查邮箱表
                String user =MailboxName;// 邮箱的用户名
               String password =Authorization; // 邮箱的密码

               Properties prop = System.getProperties();
               prop.put("mail.store.protocol", "imap");
               prop.put("mail.imap.host",Host);
               Session session = Session.getInstance(prop);
               int total = 0;
               IMAPStore store = (IMAPStore) session.getStore("imap"); // 使用imap会话机制，连接服务器
               store.connect(user, password);
               IMAPFolder folder = (IMAPFolder) store.getFolder("INBOX"); // 收件箱
        List<Map<String,Object>> list = new ArrayList<>();
        List<Message> list1 = new ArrayList<>();
            IMAPFolder imapFolder = (IMAPFolder) folder;

            //javamail中使用id命令有校验checkOpened, 所以要去掉id方法中的checkOpened();
            imapFolder.doCommand(new IMAPFolder.ProtocolCommand() {
                @Override
                public Object doCommand(IMAPProtocol p) throws  com.sun.mail.iap.ProtocolException {
                    p.id("FUTONG");
                    return null;
                }
            });


            imapFolder.open(Folder.READ_WRITE);
            //folder.open(Folder.READ_ONLY);//只读
            // folder.open(Folder.READ_WRITE);//读写
            // 获取总邮件数
            total = folder.getMessageCount();
            System.out.println("-----------------共有邮件：" + total
                    + " 封--------------");
            // 得到收件箱文件夹信息，获取邮件列表
            System.out.println("未读邮件数：" + folder.getUnreadMessageCount());
            FlagTerm ft =
                    new FlagTerm(new Flags(Flags.Flag.SEEN), false); //false代表未读，true代表已读
          //  Message[] messages = folder.getMessages();
            //Message[] messages = imapFolder.search(ft);
           Message[] messages = folder.search(ft);
            int messageNumber = 0;
            ReceiveMailUtil re = null;
        System.out.println("长度"+messages.length);
        int s=messages.length>5?messages.length-5:0;
            if(messages.length>0){
                for(int i = messages.length-1; i >=0; i--){
                    Flags flags =messages[i].getFlags();
                    if (flags.contains(Flags.Flag.SEEN))
                        System.out.println("这是一封已读邮件");
                    else {
                        System.out.println("未读邮件");
                        re = new ReceiveMailUtil((MimeMessage)messages[i]);
                        re.getMailContent((Part)messages[i]);
                        System.out.println("发送时间：" + re.getSentDate());
                        System.out.println("地址：" + re.getFrom());
                        String bodyText = re.getBodyText();
                        String txtcontent=null;
                        txtcontent=bodyText.replaceAll("<style[^>]*?>[\\s\\S]*?<\\/style>","");
                        txtcontent =txtcontent.replaceAll("</?[^>]+>", "");
                        txtcontent = txtcontent.replaceAll("<a>\\s*|\t|\r|\n|</a>", "");
                        txtcontent=txtcontent.replaceAll("&nbsp;","");
                        txtcontent=txtcontent.replaceAll("(\\w+):\\/\\/([^/:]+)(:\\d*)?([^# ]*)","");
                        txtcontent=txtcontent.replaceAll("\\&[a-zA-Z]{1,10};","");
                        txtcontent=txtcontent.replaceAll("[(/>)<]","");
                        txtcontent=txtcontent.replaceAll("\\s*|\t|\r|\n|","");
                        System.out.println("内容：" + txtcontent);
                        String e = EmailUtil.getRandomCode("验证码为", txtcontent);
                        String getyzm = EmailUtil.getyzm(e, 6);
                        Map<String,Object> map = new HashMap<>();
                        map.put("Ttime", re.getSentDate());//时间
                        map.put("site", re.getFrom());//发件人
                        map.put("txtcontent",txtcontent);//内容
                        map.put("code",getyzm);//邀请码
                        String t=re.getMailAddress("TO");
                        String[] code = t.split(",");
                        map.put("accName",code[0]);
                        map.put("MailboxName",code[1]);
                        list.add(map);
                        list1.add(messages[i]);
                    }
                    //将刚才我获取的邮件设置为已读
                    if (list.size() > 0) {
                        Message[] savedMailMessage = new Message[list1.size()];
                        list1.toArray(savedMailMessage);
                        imapFolder.setFlags(savedMailMessage, new Flags(Flags.Flag.SEEN),true);
                    }
                    System.out.println("========================================================");
                    //每封邮件都有一个MessageNumber，可以通过邮件的MessageNumber在收件箱里面取得该邮件
                   // messageNumber = messages[i].getMessageNumber();
                }
               // Message message = imapFolder.getMessage(messageNumber);
               // System.out.println(message.getContent()+message.getContentType());
            }

            // 释放资源
            if (imapFolder != null)
                imapFolder.close(true);
            if (imapFolder != null)
                store.close();
        return list;
    }
    /**
     * 从短信字符窜提取验证码
     * @param body 短信内容
     * @param YZMLENGTH  验证码的长度 一般6位或者4位
     * @return 接取出来的验证码
     */
    public static String getyzm(String body, int YZMLENGTH) {
        // 首先([a-zA-Z0-9]{YZMLENGTH})是得到一个连续的六位数字字母组合
        // (?<![a-zA-Z0-9])负向断言([0-9]{YZMLENGTH})前面不能有数字
        // (?![a-zA-Z0-9])断言([0-9]{YZMLENGTH})后面不能有数字出现


//	获得数字字母组合
    Pattern p = Pattern.compile("(?<![a-zA-Z0-9])([a-zA-Z0-9]{" + YZMLENGTH + "})(?![a-zA-Z0-9])");

//	获得纯数字
        //Pattern p = Pattern.compile("(?<![0-9])([0-9]{" + YZMLENGTH+ "})(?![0-9])");

        Matcher m = p.matcher(body);
        if (m.find()) {
            System.out.println(m.group());
            return m.group(0);
        }
        return null;
    }


    /**
     * 从短信内容中获取验证码
     * @param src
     * @param startMatch
     * @return
     */

    public static String  getRandomCode(String  startMatch, String src) {
        int i = src.indexOf(startMatch);
        String substring = src.substring(i+3, i + 15);
        return substring;

    }

//    public static void main(String[] args) {
//        List<Map<String,Object>> data = null;
//       /* //imap:qydplkcgrdvegjbj
//        try {
//            data = EmailUtil.Emali("chenxingyong520@126.com", "NDFYKPDTGIYTYQXF", "imap.126.com");
//            for (Map<String, Object> datum : data) {
//                System.out.println(datum.toString());
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//*/
//        String s="<wphy19852@126.com>";
//        String substring = s.substring(1, s.length()-1);
//        System.out.println("```:"+substring);
//
////        System.out.println(data);
////        for (Map<String, Object> datum : data) {
////            String str= (String) datum.get("txtcontent");
////            String e = EmailUtil.getRandomCode("验证码为", str);
////            System.out.println("验证码："+e);
////            String getyzm = EmailUtil.getyzm(e, 6);
////            System.out.println("验证码："+getyzm);
////        }
//    }
}

